

<template>
  <div class="container" id="container"></div>
</template>

<script lang="ts" setup>
let scene = null as any,//场景
camera = null as any,//相机
renderer = null as any,//渲染器
controls = null as any//轨道控制器
import {onMounted } from 'vue';
import * as THREE from 'three';
import { MTLLoader } from 'three/examples/jsm/loaders/MTLLoader.js';
import { OBJLoader } from 'three/examples/jsm/loaders/OBJLoader.js';
import {OrbitControls} from 'three/examples/jsm/controls/OrbitControls'
console.log(THREE)

//设置three的方法
const render = async () =>{
  //1.创建场景
  scene = new THREE.Scene();
  //2.创建相机
  camera = new THREE.PerspectiveCamera(105,window.innerWidth/window.innerHeight,0.1,1000);
  //3.设置相机位置
  camera.position.set(10,0,5);
  scene.add(camera);
  //4.建立3个坐标轴
  const axesHelper = new THREE.AxesHelper(5);
  scene.add(axesHelper);
  
  //导入模型
  // const cityModel =  await loaderObjModel(
  //   "../public/model",
  //   "广场2",
  //   "广场2"
  // )
  console.log(cityModel)

  //5.初始化渲染器
  //渲染器透明
  renderer = new THREE.WebGLRenderer({alpha:true});
  //设置渲染器尺寸大小
  renderer.setClearColor(0x228b22,0.1);
  renderer.setSize(window.innerWidth,window.innerHeight);
  //将webgl渲染的canvas内容添加到div
  let container = document.getElementById('container') as any;
  container.appendChild(renderer.domElement);
  //使用渲染器 通过相机将场景渲染出来
  renderer.render(scene,camera);
  controls = new OrbitControls(camera,renderer.domElement);
}
const animate = () =>{
    requestAnimationFrame(animate);
    renderer.render(scene,camera);
}
//加载obj模型
const loaderObjModel = (path: string,objName: string,mtlName: string) => {
  return new Promise(resolve => {
      new MTLLoader()
        .setPath(path)
        .load(mtlName + '.mtl', function (materials) {
          console.log(materials)
          materials.preload();
          // 加载obj
          new OBJLoader()
            .setPath(path)
            .setMaterials(materials)
            .load(objName + '.obj', function (object) {
              resolve(object)
            });
        });
    })
}
onMounted(()=>{
  render()
  animate()
})
</script>


<style scoped>
.container{
  width:100vw;
  height: 100vh;
}
</style>
